<?php

namespace App\Http\Controllers;

use App\Models\Room;
use App\Models\RoomUser;
use Illuminate\Http\Request;

class RoomController extends Controller
{
    /**
     * 创建房间
     */
    public function create(Request $request)
    {
        $user = $request->user;
        
        $this->validate($request, [
            'name' => 'required|max:50'
        ]);
        
        // 生成房间码
        $roomCode = Room::generateRoomCode();
        
        // 创建房间
        $room = new Room();
        $room->room_code = $roomCode;
        $room->creator_id = $user->id;
        $room->name = $request->input('name');
        $room->status = Room::STATUS_ACTIVE;
        $room->start_time = time();
        $room->save();
        
        // 添加创建者到房间
        $roomUser = new RoomUser();
        $roomUser->room_id = $room->id;
        $roomUser->user_id = $user->id;
        $roomUser->join_time = time();
        $roomUser->score_change = 0;
        $roomUser->save();
        
        return response()->json([
            'code' => 200,
            'data' => [
                'room_id' => $room->id,
                'room_code' => $room->room_code,
                'room_name' => $room->name,
                'created_at' => $room->start_time
            ],
            'message' => '房间创建成功'
        ]);
    }
    
    /**
     * 加入房间
     */
    public function join(Request $request)
    {
        $user = $request->user;
        
        $this->validate($request, [
            'room_code' => 'required|size:6'
        ]);
        
        $roomCode = strtoupper($request->input('room_code'));
        $room = Room::where('room_code', $roomCode)->first();
        
        if (!$room) {
            return response()->json([
                'code' => 404,
                'message' => '房间不存在'
            ]);
        }
        
        if ($room->status != Room::STATUS_ACTIVE) {
            return response()->json([
                'code' => 400,
                'message' => '房间已关闭'
            ]);
        }
        
        // 检查用户是否已在房间内
        $existingUser = RoomUser::where('room_id', $room->id)->where('user_id', $user->id)->first();
        if ($existingUser) {
            return response()->json([
                'code' => 200,
                'data' => [
                    'room_id' => $room->id,
                    'room_code' => $room->room_code,
                    'room_name' => $room->name
                ],
                'message' => '已在房间内'
            ]);
        }
        
        // 添加用户到房间
        $roomUser = new RoomUser();
        $roomUser->room_id = $room->id;
        $roomUser->user_id = $user->id;
        $roomUser->join_time = time();
        $roomUser->score_change = 0;
        $roomUser->save();
        
        return response()->json([
            'code' => 200,
            'data' => [
                'room_id' => $room->id,
                'room_code' => $room->room_code,
                'room_name' => $room->name
            ],
            'message' => '加入房间成功'
        ]);
    }
    
    /**
     * 获取房间信息
     */
    public function getRoom(Request $request, $id)
    {
        $user = $request->user;
        
        $room = Room::find($id);
        
        if (!$room) {
            return response()->json([
                'code' => 404,
                'message' => '房间不存在'
            ]);
        }
        
        // 检查用户是否有权限查看房间
        $roomUser = RoomUser::where('room_id', $room->id)->where('user_id', $user->id)->first();
        if (!$roomUser) {
            return response()->json([
                'code' => 403,
                'message' => '无权限查看此房间'
            ]);
        }
        
        // 获取房间内的所有用户
        $users = [];
        foreach ($room->getUsers() as $roomUser) {
            $userInfo = $roomUser->user;
            $users[] = [
                'user_id' => $userInfo->id,
                'nickname' => $userInfo->nickname,
                'avatar' => $userInfo->avatar,
                'score_change' => $roomUser->score_change,
                'join_time' => $roomUser->join_time
            ];
        }
        
        return response()->json([
            'code' => 200,
            'data' => [
                'room_id' => $room->id,
                'room_code' => $room->room_code,
                'room_name' => $room->name,
                'creator_id' => $room->creator_id,
                'status' => $room->status,
                'start_time' => $room->start_time,
                'end_time' => $room->end_time,
                'users' => $users
            ]
        ]);
    }
    
    /**
     * 关闭房间
     */
    public function close(Request $request, $id)
    {
        $user = $request->user;
        
        $room = Room::find($id);
        
        if (!$room) {
            return response()->json([
                'code' => 404,
                'message' => '房间不存在'
            ]);
        }
        
        // 只有创建者可以关闭房间
        if ($room->creator_id != $user->id) {
            return response()->json([
                'code' => 403,
                'message' => '只有创建者可以关闭房间'
            ]);
        }
        
        if ($room->status != Room::STATUS_ACTIVE) {
            return response()->json([
                'code' => 400,
                'message' => '房间已关闭'
            ]);
        }
        
        // 关闭房间
        $room->closeRoom();
        
        // 更新用户总积分
        $roomUsers = RoomUser::where('room_id', $room->id)->get();
        foreach ($roomUsers as $roomUser) {
            $roomUser->user->updateScore($roomUser->score_change);
        }
        
        return response()->json([
            'code' => 200,
            'message' => '房间关闭成功'
        ]);
    }
    
    /**
     * 获取用户参与的房间列表
     */
    public function getUserRooms(Request $request)
    {
        $user = $request->user;
        
        $roomUsers = RoomUser::where('user_id', $user->id)->orderBy('join_time', 'desc')->get();
        
        $rooms = [];
        foreach ($roomUsers as $roomUser) {
            $room = $roomUser->room;
            $rooms[] = [
                'room_id' => $room->id,
                'room_code' => $room->room_code,
                'room_name' => $room->name,
                'status' => $room->status,
                'creator_id' => $room->creator_id,
                'is_creator' => $room->creator_id == $user->id,
                'score_change' => $roomUser->score_change,
                'join_time' => $roomUser->join_time,
                'start_time' => $room->start_time,
                'end_time' => $room->end_time
            ];
        }
        
        return response()->json([
            'code' => 200,
            'data' => [
                'rooms' => $rooms
            ]
        ]);
    }
}